<?php

namespace Admin\Controller;

use Think\Upload;

class UploadController extends AdminController {

    protected $exts = [
        'mimes' => 'image/jpeg,image/png,image/jpg',
        'exts' => 'jpg,png,jpeg',
    ];

    private $_app;

    public function __construct($config = []) {
        parent::__construct();
        if ($config) {
            $this->exts = $config;
        }

        $this->_app = new Upload($this->exts);
    }

    /**
     * 普通图片上传  目录 images/
     * @param $file
     * @return string
     */
    protected function uploadImage($file) {

        $this->_app->rootPath = $this->_app->rootPath . 'images/';
        if (!$file = $this->_app->uploadOne($file)) {
            $this->error($this->_app->getError());
        }
        $url = trim($this->_app->rootPath, '.') . $file['savepath'] . $file['savename'];

        return $url;
    }

    public function image() {
        $callback = I('callback');

        $this->_app->rootPath = $this->_app->rootPath . 'images/';
        if (!$file = $this->_app->uploadOne($_FILES['upfile'])) {
            $fileInfo = [
                'state' => $this->_app->getError()
            ];
        } else {
            $url = trim($this->_app->rootPath, '.') . $file['savepath'] . $file['savename'];
            $fileInfo = [
                'originalName' => $file['name'],
                "name" => $file['savename'],
                "url" => $url,
                "size" => $file['size'],
                "type" => $file['type'],
                "state" => 'SUCCESS',
            ];
        }

        if ($callback) {
            echo '<script>' . $callback . '(' . json_encode($fileInfo) . ')</script>';
        } else {
            echo json_encode($fileInfo);
        }
        exit;
    }

}
